<?php

namespace app\common\model;

use app\common\model\BaseModel;
use Exception;
use think\facade\Config;


class Order extends BaseModel
{
    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'start_time_begin_text',
        'start_time_end_text',
        'end_time_text',
        'create_by_driver_text',
        'type_text',
        'status_text',
        'begin_time_text',
        'finish_time_text',
        'cancel_time_text',
        'create_time_text'
    ];
    

    
    public function getCreateByDriverList()
    {
        return ['0' => '乘客创建', '1' => '司机创建'];
    }

    public function getTypeList()
    {
        return ['monopoly' => '包车', 'share' => '拼车', 'cargo' => '寄货'];
    }

    public function getHasMonopolyList()
    {
        return ['0' => '不含包车子订单', '1' => '含有包车子订单'];
    }

    public function getHasShareList()
    {
        return ['0' => '不含拼车子订单', '1' => '含有拼车子订单'];
    }

    public function getHasCargoList()
    {
        return ['0' => '不含寄货子订单', '1' => '含有寄货子订单'];
    }

    public function getStatusList()
    {
        return [
            '1' => '未接单',
            '2' => '已接单',
            '3' => '已出发',
            '4' => '已到达起点',
            '5' => '服务中',
            '6' => '已到达终点',
            '7' => '已完成',
            '8' => '已评价',
            '10' => '已取消'
        ];
    }


    public function getStartTimeBeginTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time_begin']) ? $data['start_time_begin'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStartTimeEndTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time_end']) ? $data['start_time_end'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateByDriverTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_by_driver']) ? $data['create_by_driver'] : '');
        $list = $this->getCreateByDriverList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getBeginTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['begin_time']) ? $data['begin_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFinishTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finish_time']) ? $data['finish_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCancelTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['cancel_time']) ? $data['cancel_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setBeginTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFinishTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCancelTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id')->joinType('LEFT');
    }


    public function driverinfo()
    {
        return $this->belongsTo('DriverInfo', 'driver_id', 'user_id')->joinType('LEFT');
    }


    public function suborder()
    {
        return $this->hasMany('SubOrder', 'parent_id', 'id');
    }

    /**
     * 创建打车子订单
     * @throws Exception
     */
    public static function createPassengerOrder($type,$distance,$user_id){
        $passenger=[
            'adult'         =>request()->param('adult')?:0,
            'child'         =>request()->param('child')?:0,
            'baby'          =>request()->param('baby')?:0,

            'luggage_type'  =>request()->param('luggage_type')?:'',
            'luggage_weight'=>request()->param('luggage_weight')?:0,
            'luggage_size'  =>request()->param('luggage_size')?:'',

            'pet_name'      =>request()->param('pet_name')?:'',
            'pet_weight'    =>request()->param('pet_weight')?:0,
            'pet_cage'      =>request()->param('pet_cage')?:0,
            'pet_vaccinated'=>request()->param('pet_vaccinated')?:0,

            'requirement'   =>request()->param('requirement')?:'',
            'tips'          =>request()->param('tips')?:0,
            'create_time'   =>time()
        ];
        $sub_order=[
            'user_id'       =>$user_id,
            'type'          =>$type,
            'status'        =>1,
            'pay_status'    =>0,
            'car_price'     =>0,
            'luggage_price' =>0,
            'pet_price'     =>0,
            'tips'          =>$passenger['tips'],
            'coupon_id'     =>0,
            'coupon_price'  =>0,
            'create_time'   =>$passenger['create_time'],

            'person'=>0,
            'weight'=>0
        ];

        $sub_order['person']=$passenger['adult']+$passenger['child']+$passenger['baby'];
        /*if($passenger['adult']<=0){
            throw new Exception('至少要设置1名成年乘车人');
        }*/
        if($sub_order['person']<=0){
            throw new Exception('请选择乘车人数');
        }
        if($sub_order['person']>4){
            throw new Exception('乘车人数不能多于4人');
        }

        //if($passenger['luggage_type']||$passenger['luggage_weight']||($passenger['luggage_size']&&$passenger['luggage_size']!='**')){
        if($passenger['luggage_weight']||($passenger['luggage_size']&&$passenger['luggage_size']!='**')){
            /*if(!$passenger['luggage_type'])
                throw new Exception('请选择行李类型');*/
            if(!$passenger['luggage_weight'])
                throw new Exception('请输入行李重量');
            if(!$passenger['luggage_size'])
                throw new Exception('请输入行李尺寸');
            $sub_order['weight']=$passenger['luggage_weight'];
        }

        if($passenger['pet_name']||$passenger['pet_weight']||$passenger['pet_cage']||$passenger['pet_vaccinated']){
            if(!$passenger['pet_name'])
                throw new Exception('请输入动物名');
            if(!$passenger['pet_weight'])
                throw new Exception('请输入动物重量');
            if(!in_array($passenger['pet_cage'],[0,1]))
                throw new Exception('请选择动物是否装笼');
            if(!in_array($passenger['pet_vaccinated'],[0,1]))
                throw new Exception('请选择动物是否已接种疫苗');
        }

        if($type=='monopoly'){
            $sub_order['car_price']=bcadd(Config::get('site.monopoly_car_base_price')?:0,bcmul(Config::get('site.monopoly_car_km_price'),$distance,2),2);

            if($passenger['luggage_weight']&&$passenger['luggage_weight']>25){
                $over_weight=bcsub($passenger['luggage_weight'],25,0);
                $sub_order['luggage_price']=bcadd(Config::get('site.monopoly_luggage_base_price')?:0,bcmul(Config::get('site.monopoly_luggage_kg_price'),$over_weight,2),2);
            }

            if($passenger['pet_name']){
                $sub_order['pet_price']=bcadd(Config::get('site.monopoly_pet_base_price')?:0,bcmul(Config::get('site.monopoly_pet_kg_price'),$passenger['pet_weight'],2),2);
            }
        }
        else{
            $car_price=bcadd(Config::get('site.share_car_base_price')?:0,bcmul(Config::get('site.share_car_km_price'),$distance,2),2);

            /* 儿童半价，婴儿四分之一 */
            $person_times=bcadd(
                bcadd(
                    bcmul($passenger['child'],0.5,2),
                    bcmul($passenger['baby'],0.5,2),2)
                ,$passenger['adult'],2);
            $one_price=bcadd(Config::get('site.share_adult_base_price')?:0,bcmul(Config::get('site.share_adult_km_price'),$distance,2),2);
            $person_price=bcmul($person_times,$one_price,2);
            $sub_order['car_price']=bcadd($car_price,$person_price,2);


            if($passenger['luggage_weight']&&$passenger['luggage_weight']>25){
                $over_weight=bcsub($passenger['luggage_weight'],25,0);
                $sub_order['luggage_price']=bcadd(Config::get('site.monopoly_luggage_base_price')?:0,bcmul(Config::get('site.monopoly_luggage_kg_price'),$over_weight,2),2);
            }

            if($passenger['pet_name']){
                $sub_order['pet_price']=bcadd(Config::get('site.monopoly_pet_base_price')?:0,bcmul(Config::get('site.monopoly_pet_kg_price'),$passenger['pet_weight'],2),2);
            }

        }

        $sub_order['pay_price']=$sub_order['price']=bcadd(bcadd($sub_order['car_price'],$sub_order['luggage_price'],2),bcadd($sub_order['pet_price'],$passenger['tips'],2),2);


        //匹配优惠券
        if($sub_order['price']>$sub_order['tips']){
            $coupon=CouponLog::bestCoupon(bcsub($sub_order['price'],$sub_order['tips'],2),$user_id)?:[];
            if($coupon){
                $sub_order['coupon_id']=$coupon['id'];
                $sub_order['coupon_price']=($sub_order['pay_price']>=$coupon['coupon']['discount_money'])?$coupon['coupon']['discount_money']:$sub_order['pay_price'];
                $sub_order['pay_price']=bcsub($sub_order['price'],$coupon['coupon']['discount_money'],2);
            }
        }
        if($sub_order['pay_price']<0){
            $sub_order['pay_price']=0;
            $sub_order['pay_status']=3;
        }

        $sub_order['passenger']=$passenger;
        return $sub_order;
    }


    /**
     * 创建寄货子订单
     */
    public static function createCargoOrder($distance,$user_id){
        $cargo=[
            'sender'        =>request()->param('sender')?:'',
            'sender_phone'  =>request()->param('sender_phone')?:'',
            'receiver'      =>request()->param('receiver')?:'',
            'receiver_phone'=>request()->param('receiver_phone')?:'',

            'name'          =>request()->param('name')?:'',
            'type'          =>request()->param('cargo_type')?:'',
            'weight'        =>request()->param('weight')?:0,
            'size'          =>request()->param('size')?:'',
            'packed'        =>request()->param('packed')?:'',
            'img'           =>request()->param('img')?:'',
            'create_time'   =>time(),
        ];
        $sub_order=[
            'user_id'       =>$user_id,
            'type'          =>'cargo',
            'status'        =>1,
            'pay_status'    =>0,
            'car_price'     =>0,
            'luggage_price' =>0,
            'pet_price'     =>0,
            'tips'          =>0,
            'coupon_id'     =>0,
            'coupon_price'  =>0,
            'create_time'   =>$cargo['create_time'],

            'person'=>0,
            'weight'=>0
        ];

        if(!$cargo['sender']||!$cargo['sender_phone']){
            throw new Exception('请输入发件人信息');
        }
        if(!$cargo['receiver']||!$cargo['receiver_phone']){
            throw new Exception('请输入收件人信息');
        }
        if(!$cargo['weight']){
            throw new Exception('请输入货物重量');
        }
        $sub_order['weight']=$cargo['weight'];

        $step1=bcadd(Config::get('site.cargo_basic_price')?:0,bcmul(Config::get('site.cargo_kg_price'),$cargo['weight'],2),2);
        $sub_order['pay_price']=$sub_order['price']=$sub_order['car_price']=bcadd($step1,bcmul(Config::get('site.cargo_km_price'),$distance,2),2);

        //匹配优惠券
        if($sub_order['price']>$sub_order['tips']){
            $coupon=CouponLog::bestCoupon(bcsub($sub_order['price'],$sub_order['tips'],2),$user_id)?:[];
            if($coupon){
                $sub_order['coupon_id']=$coupon['id'];
                $sub_order['coupon_price']=($sub_order['pay_price']>=$coupon['coupon']['discount_money'])?$coupon['coupon']['discount_money']:$sub_order['pay_price'];
                $sub_order['pay_price']=bcsub($sub_order['price'],$coupon['coupon']['discount_money'],2);
            }
        }
        if($sub_order['pay_price']<0){
            $sub_order['pay_status']=3;
            $sub_order['pay_price']=0;
        }

        $sub_order['cargo']=$cargo;
        return $sub_order;
    }
}
